import fs from 'fs'
import path from 'path'

/**
 * 缓存类型配置
 */
const CACHE_TYPES = {
  trf: {
    name: 'TRF结果缓存',
    directory: 'trf-results',
    extensions: ['.json'],
    description: 'TRF API处理结果缓存文件'
  },
  uploads: {
    name: '上传文件缓存',
    directory: 'uploads',
    extensions: ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt'],
    description: '用户上传的原始文件'
  },
  processed: {
    name: '处理结果缓存',
    directory: 'processed',
    extensions: ['.pdf', '.json'],
    description: '文件处理后的结果文件'
  },
  temp: {
    name: '临时文件缓存',
    directory: 'temp',
    extensions: ['.tmp', '.pdf', '.json', '.txt'],
    description: '处理过程中产生的临时文件'
  },
  logs: {
    name: '系统日志文件',
    directory: 'logs',
    extensions: ['.txt', '.log'],
    description: '应用运行产生的日志文件（运行中日志无法删除，将清空内容）'
  }
}

/**
 * 获取指定缓存类型的统计信息
 * @param {string} cacheType - 缓存类型
 * @returns {Object} 缓存统计信息
 */
export async function getCacheStatsByType(cacheType) {
  try {
    const config = CACHE_TYPES[cacheType]
    if (!config) {
      throw new Error(`不支持的缓存类型: ${cacheType}`)
    }

    const cacheDir = path.join(process.cwd(), config.directory)
    
    if (!fs.existsSync(cacheDir)) {
      return {
        type: cacheType,
        name: config.name,
        description: config.description,
        totalFiles: 0,
        totalSize: 0,
        files: []
      }
    }

    const allFiles = fs.readdirSync(cacheDir)
    const validFiles = allFiles.filter(file => {
      const ext = path.extname(file).toLowerCase()
      return config.extensions.includes(ext) || config.extensions.length === 0
    })

    let totalSize = 0
    const fileStats = []

    for (const file of validFiles) {
      const filePath = path.join(cacheDir, file)
      let stats
      try {
        stats = fs.statSync(filePath)
      } catch (e) {
        console.warn(`读取文件状态失败: ${filePath}`, e.message)
        // 无法读取状态（可能被占用），返回最基本信息
        fileStats.push({
          filename: file,
          size: 0,
          createdAt: null,
          modifiedAt: null,
          accessedAt: null,
          age: null,
          locked: e.code === 'EPERM'
        })
        continue
      }
      
      if (stats.isFile()) {
        totalSize += stats.size
        
        // 尝试读取文件元数据（如果是JSON文件）
        let metadata = {}
        if (path.extname(file).toLowerCase() === '.json') {
          try {
            const content = fs.readFileSync(filePath, 'utf8')
            const data = JSON.parse(content)
            metadata = {
              orderNo: data.order_no || file.replace('.json', ''),
              cachedAt: data.cached_at || stats.birthtime.toISOString()
            }
          } catch (e) {
            // 忽略JSON解析错误
          }
        }

        fileStats.push({
          filename: file,
          size: stats.size,
          createdAt: stats.birthtime,
          modifiedAt: stats.mtime,
          accessedAt: stats.atime,
          age: Date.now() - stats.mtime.getTime(),
          ...metadata
        })
      }
    }

    // 按修改时间排序（最新的在前）
    fileStats.sort((a, b) => new Date(b.modifiedAt) - new Date(a.modifiedAt))

    return {
      type: cacheType,
      name: config.name,
      description: config.description,
      totalFiles: validFiles.length,
      totalSize,
      files: fileStats
    }
  } catch (error) {
    console.error(`获取${cacheType}缓存统计信息时出错:`, error)
    throw error
  }
}

/**
 * 获取所有缓存类型的统计信息
 * @returns {Object} 所有缓存统计信息
 */
export async function getAllCacheStats() {
  try {
    const allStats = {}
    let totalFiles = 0
    let totalSize = 0

    for (const [type, config] of Object.entries(CACHE_TYPES)) {
      const stats = await getCacheStatsByType(type)
      allStats[type] = stats
      totalFiles += stats.totalFiles
      totalSize += stats.totalSize
    }

    return {
      summary: {
        totalFiles,
        totalSize,
        cacheTypes: Object.keys(CACHE_TYPES).length
      },
      details: allStats
    }
  } catch (error) {
    console.error('获取所有缓存统计信息时出错:', error)
    throw error
  }
}

/**
 * 清理指定类型的缓存文件
 * @param {string} cacheType - 缓存类型
 * @param {Object} options - 清理选项
 * @param {number} options.maxAge - 最大保留时间（毫秒）
 * @param {number} options.maxFiles - 最大保留文件数
 * @param {Array<string>} options.specificFiles - 指定要删除的文件名列表
 * @returns {Object} 清理结果
 */
export async function cleanCacheByType(cacheType, options = {}) {
  try {
    const config = CACHE_TYPES[cacheType]
    if (!config) {
      throw new Error(`不支持的缓存类型: ${cacheType}`)
    }

    const cacheDir = path.join(process.cwd(), config.directory)
    
    if (!fs.existsSync(cacheDir)) {
      return {
        success: true,
        cacheType,
        deletedFiles: [],
        message: `${config.name}目录不存在`
      }
    }

    const stats = await getCacheStatsByType(cacheType)
    let filesToDelete = []

    // 如果指定了特定文件，只删除这些文件
    if (options.specificFiles && options.specificFiles.length > 0) {
      filesToDelete = stats.files.filter(file => 
        options.specificFiles.includes(file.filename) || 
        options.specificFiles.includes(file.orderNo)
      )
    } else {
      // 如果没有指定任何清理条件，默认删除所有文件
      let hasCleaningOptions = false
      
      // 基于时间清理
      if (options.maxAge) {
        const oldFiles = stats.files.filter(file => file.age > options.maxAge)
        filesToDelete = filesToDelete.concat(oldFiles)
        hasCleaningOptions = true
      }
      
      // 基于文件数量清理（保留最新的文件）
      if (options.maxFiles && stats.files.length > options.maxFiles) {
        const excessFiles = stats.files.slice(options.maxFiles)
        filesToDelete = filesToDelete.concat(excessFiles)
        hasCleaningOptions = true
      }
      
      // 如果没有指定任何清理条件，删除所有文件
      if (!hasCleaningOptions) {
        filesToDelete = stats.files
      }
    }

    // 去重
    filesToDelete = filesToDelete.filter((file, index, self) => 
      index === self.findIndex(f => f.filename === file.filename)
    )

    const deletedFiles = []
    let deletedSize = 0

    for (const file of filesToDelete) {
      const filePath = path.join(cacheDir, file.filename)
      try {
        fs.unlinkSync(filePath)
        deletedFiles.push({
          filename: file.filename,
          size: file.size,
          modifiedAt: file.modifiedAt
        })
        deletedSize += file.size
        console.log(`已删除${config.name}文件: ${file.filename}`)
      } catch (deleteError) {
        // 对日志文件做特殊处理：无法删除则清空内容
        if (config.directory === 'logs' && deleteError?.code === 'EPERM') {
          try {
            fs.truncateSync(filePath, 0)
            deletedFiles.push({
              filename: file.filename,
              size: file.size,
              modifiedAt: file.modifiedAt,
              truncated: true
            })
            deletedSize += file.size
            console.log(`无法删除日志文件，已清空内容: ${file.filename}`)
          } catch (truncateError) {
            console.error(`清空日志文件内容失败 ${file.filename}:`, truncateError)
          }
        } else {
          console.error(`删除文件 ${file.filename} 时出错:`, deleteError)
        }
      }
    }

    return {
      success: true,
      cacheType,
      deletedFiles,
      deletedSize,
      message: `成功清理 ${deletedFiles.length} 个${config.name}文件，释放空间 ${(deletedSize / 1024 / 1024).toFixed(2)} MB`
    }
    
  } catch (error) {
    console.error(`清理${cacheType}缓存时出错:`, error)
    throw error
  }
}

/**
 * 清理所有指定类型的缓存文件
 * @param {Array<string>} cacheTypes - 要清理的缓存类型列表
 * @returns {Object} 清理结果
 */
export async function clearAllCache(cacheTypes = []) {
  try {
    const results = []
    let totalDeletedFiles = 0
    let totalDeletedSize = 0

    for (const cacheType of cacheTypes) {
      if (!CACHE_TYPES[cacheType]) {
        console.warn(`跳过不支持的缓存类型: ${cacheType}`)
        continue
      }

      try {
        const stats = await getCacheStatsByType(cacheType)
        const result = await cleanCacheByType(cacheType, {})
        
        // 删除所有文件
        const config = CACHE_TYPES[cacheType]
        const cacheDir = path.join(process.cwd(), config.directory)
        
        if (fs.existsSync(cacheDir)) {
          const allFiles = stats.files
          const deletedFiles = []
          let deletedSize = 0

          for (const file of allFiles) {
            const filePath = path.join(cacheDir, file.filename)
            try {
              fs.unlinkSync(filePath)
              deletedFiles.push({
                filename: file.filename,
                size: file.size
              })
              deletedSize += file.size
            } catch (deleteError) {
              // 对日志文件做特殊处理：无法删除则清空内容
              if (config.directory === 'logs' && deleteError?.code === 'EPERM') {
                try {
                  fs.truncateSync(filePath, 0)
                  deletedFiles.push({
                    filename: file.filename,
                    size: file.size,
                    truncated: true
                  })
                  deletedSize += file.size
                  console.log(`无法删除日志文件，已清空内容: ${file.filename}`)
                } catch (truncateError) {
                  console.error(`清空日志文件内容失败 ${file.filename}:`, truncateError)
                }
              } else {
                console.error(`删除文件 ${file.filename} 时出错:`, deleteError)
              }
            }
          }

          results.push({
            cacheType,
            name: config.name,
            deletedFiles: deletedFiles.length,
            deletedSize
          })

          totalDeletedFiles += deletedFiles.length
          totalDeletedSize += deletedSize
        }
      } catch (typeError) {
        console.error(`清理${cacheType}缓存时出错:`, typeError)
        results.push({
          cacheType,
          error: typeError.message
        })
      }
    }

    return {
      success: true,
      results,
      summary: {
        totalDeletedFiles,
        totalDeletedSize,
        message: `成功清理 ${totalDeletedFiles} 个文件，释放空间 ${(totalDeletedSize / 1024 / 1024).toFixed(2)} MB`
      },
      message: `批量清理完成，共处理 ${cacheTypes.length} 种缓存类型`
    }
    
  } catch (error) {
    console.error('批量清理缓存时出错:', error)
    throw error
  }
}

/**
 * 获取支持的缓存类型列表
 * @returns {Array} 缓存类型配置列表
 */
export function getSupportedCacheTypes() {
  return Object.entries(CACHE_TYPES).map(([type, config]) => ({
    type,
    name: config.name,
    description: config.description,
    directory: config.directory,
    extensions: config.extensions
  }))
}